/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function (s, p) {
  const sN = s.length,
    pN = p.length;
  if (sN < pN) return [];

  const result = [];
  const pCount = Array(26).fill(0);
  const sCount = Array(26).fill(0);

  for (let i = 0; i < pN; i++) {
    pCount[p.charCodeAt(i) - 'a'.charCodeAt(0)]++;
    sCount[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
  }

  if (arraysEqual(pCount, sCount)) {
    result.push(0);
  }

  for (let i = pN; i < sN; i++) {
    sCount[s.charCodeAt(i) - 'a'.charCodeAt(0)]++;
    sCount[s.charCodeAt(i - pN) - 'a'.charCodeAt(0)]--;

    if (arraysEqual(pCount, sCount)) {
      result.push(i - pN + 1);
    }
  }

  return result;
};

function arraysEqual(arr1, arr2) {
  for (let i = 0; i < 26; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }
  }
  return true;
}
